#include "Log/Log.hh"
#include "Configuration.hh"

using std::cout;
using std::cerr;
using std::endl;
using std::ios;
using std::string;
using namespace log4cpp;

Log* Log::_instance = nullptr;
Category& Log::_sub = Category::getInstance(string("斛珠"));

Log* Log::createLog(int output){
    if(_instance == nullptr){
        _instance = new Log(output);
    }
    return _instance;
}


void Log::destroyLog(){
    if(_instance != nullptr){
        delete _instance;
        _instance = nullptr;
    }
    
}
Log::Log(int output){

    auto& conf_map = Configuration::createConfig()->getConfigMap();
    if((output & 0x001) != 0){
        // 输出到终端
        outputConsole();
    }
    if((output & 0x2) != 0){
        // 输出到文件
        outputFile(conf_map["logFile"][0]);
    }
    if((output & 0x4) != 0){
        // 输出到回卷文件
        outputRoll(conf_map["logRoll"][0]);
    }

    int level = atoi(conf_map["level"][0].c_str());
    _sub.setPriority(level);
}


Log::~Log(){
    if(_ptn1){delete _ptn1; _ptn1 = nullptr;}
    if(_ptn2){delete _ptn2; _ptn2 = nullptr;}
    if(_ptn3){delete _ptn3; _ptn3 = nullptr;}
    if(_appender1){delete _appender1; _appender1 = nullptr;}
    if(_appender2){delete _appender2; _appender2 = nullptr;}
    if(_appender3){delete _appender3; _appender3 = nullptr;}
}


void Log::outputConsole(){
    _ptn1 = new PatternLayout();
    _ptn1->setConversionPattern("%d %c [%p] %m %n");
    _appender1 = new OstreamAppender("Console", &cerr);
    _appender1->setLayout(_ptn1);
    _sub.addAppender(_appender1);
    cerr << "Console output success!\n";
}
void Log::outputFile(const string& file){
    

    _ptn2 = new PatternLayout();
    _ptn2->setConversionPattern("%d %c [%p] %m %n");
    _appender2 = new FileAppender("File", file);
    _appender2->setLayout(_ptn2);
    _sub.addAppender(_appender2);
    cerr << "File output success!\n";
}
void Log::outputRoll(const string& roll){
    _ptn3 = new PatternLayout();
    _ptn3->setConversionPattern("%d %c [%p] %m %n");
    _appender3 = new RollingFileAppender("Roll", roll, 1 * 1024 * 1024, 10);
    _appender3->setLayout(_ptn3);
    _sub.addAppender(_appender3);
    cerr << "Roll output success!\n";
}